package com.thirteenClassicsServer.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.thirteenClassics.dto.BookDto;
import com.thirteenClassics.dto.BookPageQueryDTO;
import com.thirteenClassics.dto.CommonDTO;
import com.thirteenClassics.dto.PictureCatalogQueryDTO;
import com.thirteenClassics.entity.Book;
import com.thirteenClassics.exception.BaseException;
import com.thirteenClassics.result.PageResult;
import com.thirteenClassics.result.Result;
import com.thirteenClassics.vo.CatalogVO;
import com.thirteenClassicsServer.mapper.BookMapper;
import com.thirteenClassicsServer.service.IBookService;
import com.thirteenClassicsServer.service.ICatalogBookService;
import com.thirteenClassicsServer.service.IPictureService;
import com.thirteenClassicsServer.service.impl.FileServiceImpl;
import com.thirteenClassicsServer.service.impl.XmlParseService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private IBookService bookService;

    @Resource
    private IPictureService pictureService;

    @Resource
    private ICatalogBookService catalogBookService;

    @Resource
    private BookMapper bookMapper;

    @Autowired
    private FileServiceImpl fileService;

    @Autowired
    private XmlParseService xmlParseService;

    //TODO id或者书名查询
    @GetMapping()
    public Result<PageResult> selectbook(BookPageQueryDTO bookPageQueryDTO) {
        log.info("分页查询：{}", bookPageQueryDTO);
        PageResult pageResult = bookService.pageQuery(bookPageQueryDTO);
        return Result.success(pageResult);
    }


    @GetMapping("/jdb")
    public Result<PageResult> selectbookjdb(BookPageQueryDTO bookPageQueryDTO) {
        log.info("分页查询：{}", bookPageQueryDTO);
        PageResult pageResult = bookService.pageQueryjdb(bookPageQueryDTO);
        return Result.success(pageResult);
    }


    @GetMapping("/{id}")
    public Result<BookDto> selectbookByid(@PathVariable("id") Long id) {
        log.info("查询：{}", id);
        Book book = bookService.selectbookById(id);
        BookDto bookDto = new BookDto();
        BeanUtils.copyProperties(book, bookDto);

        String lang = book.getBookLang();
        // 使用空格分隔字符串并转换为列表
        ArrayList<String> characterList = new ArrayList<>(Arrays.asList(lang.trim().split(" ")));

        bookDto.setBookLang(characterList);

        return Result.success(bookDto);
    }

    @PostMapping
    @Transactional
    public Result<Long> save(@RequestBody BookDto bookDto) throws Exception {
        log.info("新增书目：{}", bookDto);


        Book book = new Book();
        BeanUtils.copyProperties(bookDto, book);
        String langs = changeLanguage(bookDto.getBookLang());
        book.setBookLang(langs);


        Long id = bookService.saveBook(book);

        //1.与目录表对应
        int inf = catalogBookService.updateMinorityBkId(bookDto.getBookName(), langs, id);
        if (inf == 0) {
            throw new BaseException("该书目目录录入错误");
        }

        //2.图片与目录表对应
        PictureCatalogQueryDTO pictureCatalogQueryDTO = new PictureCatalogQueryDTO();
        pictureCatalogQueryDTO.setBookName(book.getBookName());
        pictureCatalogQueryDTO.setBookId(book.getId());
        pictureCatalogQueryDTO.setBookLang(langs);
        catalogBookService.insertcatalog(pictureCatalogQueryDTO);


        bookMapper.updateFlag(id);

        return Result.success(id);
    }


    public String changeLanguage(List<String> langsList) {
        Collections.sort(langsList);
        // 连接排序后的语言，使用空格作为分隔符
        return langsList.stream()
                .collect(Collectors.joining(" "));
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("书目批量删除：{}", ids);
        bookService.deleteBatch(ids);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody BookDto bookDto) {
        log.info("修改书目：{}", bookDto);
        Book book = new Book();
        BeanUtils.copyProperties(bookDto, book);
        String langs = "";
        for (String lang : bookDto.getBookLang()) {
            langs = langs + " " + lang;
        }
        book.setBookLang(langs);
        bookService.updateBook(book);
        return Result.success();
    }

    //查询当前书的当前index目录名字和总目录数
    @GetMapping("/catalog")
    public Result<CatalogVO> selectCatalogbook(PictureCatalogQueryDTO pictureCatalogQueryDTO) {
        log.info("选择书本最小目录：{}", pictureCatalogQueryDTO);
        CatalogVO catalogVO = pictureService.selectName(pictureCatalogQueryDTO);
        return Result.success(catalogVO);
    }

    //导入图片
    @PostMapping("/importPic")
    public Result importPic(@RequestBody CommonDTO commonDTO) {
        log.info("导入图片：{}", commonDTO);
        pictureService.importPicInsert(commonDTO);
        return Result.success();
    }


}
